package com.hskn.hss.module.log.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hskn.hss.exception.HssException;
import com.hskn.hss.module.log.entity.Log;
import com.hskn.hss.module.log.mapper.LogMapper;
import com.hskn.hss.module.log.service.ILogService;
import com.hskn.hss.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hskn
 * @since 2021-04-30
 */
@Service
public class LogServiceImpl extends ServiceImpl<LogMapper, Log> implements ILogService {

    @Resource
    private LogMapper logMapper;

    @Override
    public JSONObject mList(JSONObject params) throws HssException {
        String account = params.getString("account");
        String content = params.getString("content");
        Long page = StringUtils.isEmpty(params.getLong("page")) ? 1 : params.getLong("page");
        Long size = StringUtils.isEmpty(params.getLong("size")) ? 10 : params.getLong("size");
        String startDate = params.getString("startDate");
        String endDate = params.getString("endDate");
        JSONObject json = new JSONObject();
        QueryWrapper<Log> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().orderByDesc(Log::getCreateTime);
        if (Objects.nonNull(startDate) && Objects.nonNull(endDate)){
            queryWrapper.lambda().between(Log::getCreateTime, startDate, endDate);
        }
        if (StringUtils.isNotEmpty(account)) {
            queryWrapper.lambda().like(Log::getAccount, account);
        }
        if (StringUtils.isNotEmpty(content)) {
            queryWrapper.lambda().like(Log::getContent, content);
        }
        Page<Log> noticePage = new Page<>(page, size, true);
        IPage<Log> iPage = logMapper.selectPage(noticePage, queryWrapper);
        json.put("total", iPage.getTotal());
        json.put("size", iPage.getSize());
        json.put("pages", iPage.getPages());
        json.put("current", iPage.getCurrent());
        json.put("notices", iPage.getRecords());
        return json;
    }

    @Override
    public void add(JSONObject params) throws HssException {
        Log log = JSON.parseObject(params.toJSONString(), Log.class);
        logMapper.insert(log);
    }
}
